<?php

class MembersController extends AppController {
	
	var $helpers = array('Html','Markdown','Javascript','Ajax');
	
	function labelsForAdmin($format = null) {
		$this->adminOnly();
		
		$this->layout = 'ajax';
		$addresses = $this->Member->formatAddresses($this->Member->findAll('Member.auth_type = "' . AUTH_MEM . '"',null,'Member.last_name ASC, Member.first_name ASC'));
		$this->set('addresses',$addresses);
		$this->set('format',$format);
	}
	
	function show($condition = AUTH_MEM, $page = 1, $view = null) {
		if ($this->checkSession()) {
		} else {
			$this->forceLogin();
		}
		$baseActions = array(
			'administrator'=>array(
				array('View Current Basket','/members/basket/','member_id'),
				array('Edit Member Info','/members/edit/','member_id'),
				array('Edit Producer Info','/members/editProducer/','member_id'),
				array('Delete Member','/members/delete/','member_id')
				)
		);
		
		$options = array();
		
		switch($condition) {
			case "votes":
			case "volunteer":
			case "board":
			case "discontinued":
				$options[$condition] = true;
			break;
			case "paid":
			case "unpaid":
			case "due":
				$options[$condition] = true;
				$options['auth_type'] = AUTH_MEM;
			break;
			case "ordered":
				$options['order_open'] = $this->deliveryId;
			break;
			default:
				$options["auth_type"] = $condition;
			break;
		}
		
		$order = null;
		
		if ($condition != 'votes') {
			$baseActions['administrator'][] = array('Mark as Paid', '/members/paid/' . $condition . '/','member_id');
		}
		
		if ($condition == AUTH_PROD) {
			$baseActions['administrator'][] = array('Check In Producer','/producers/setupForCheckIn/','producer_id',AUTH_PROD);
			$baseActions['administrator'][] = array('View Invoice','/producers/invoicing/','producer_id',AUTH_PROD);
			$baseActions['administrator'][] = array('Manage Products', '/products/manage/all/1/', 'producer_id', AUTH_PROD);
			$order = 'Member.business_name ASC';
		}
		
		$limit = ($view == 'contact') ? null : 50;
		

		$names = array(
			AUTH_MEM => "Users",
			AUTH_PROD => "Producers",
			AUTH_CASH => "Cashiers",
			AUTH_ADMIN => "Administrators",
			AUTH_RTE => "Route Managers",
			'discontinued' => "Discontinued Members",
			'ordered' => "People that have ordered this cycle",
			'votes' => "Voting Members",
			'volunteer' => 'Volunteers',
			'board' => "Board Members",
			'unpaid' => 'Unpaid Members',
			'paid' => 'Paid Members',
			'due' => 'Coming Due Members'
		);

		$this->pageTitle = $names[$condition] . ' List, Page ' . $page;

		$this->set('names', $names);
		$this->set('authType', $condition);
		$this->set('page', $page);
		$this->set('limit', $limit);
		$this->set('count', $this->Member->count_c_find($options));
		$this->set("members", $this->Member->c_find($options, $order, $limit, $page));
		$this->set("actions",$baseActions);
		if ($view !== null) {
			$this->render($view);
		}
	}
	
	function find($field = null, $value = null) {
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_CASH)) {
				//allow search
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		
		$this->layout = 'ajax';
		$baseActions = array(
			'administrator'=>array(
				array('View Current Basket','/members/basket/','member_id'),
				array('Edit Member Info','/members/edit/','member_id'),
				array('Edit Producer Info','/members/editProducer/','member_id'),
				array('Delete Member','/members/delete/','member_id'),
				array('Mark as Paid', '/members/paid/search/','member_id')
				),
			AUTH_CASH=>array(
				array('View Current Basket','/members/basket/','member_id'),
				array('Pick for Transfer','/members/transfer/','member_id'),
				array('Mark as Paid', '/members/paid/search/','member_id')
				)
		);
		$this->set("actions",$baseActions);
		
		if (!empty($this->data)) {
			$field = $this->data['Member']['field'];
			$value = $this->data['Member']['value'];
		}
		
		$members = ($field !== null && $value !== null) ? $this->Member->findAll($field . ' LIKE "%' . $value . '%"') : array();
		$this->set('members', $members);
	}
	
	function search($field = null, $value = null) {
		if ($this->checkSession()) {
			if($this->checkLevel(AUTH_CASH)) {
				//allow search
			} else {
				$this->notAuth();
			}
		} else {
			$this->forceLogin();
		}
		
		$this->pageTitle = 'Member Search';
		
		if (!empty($this->data)) {
			$field = $this->data['Member']['field'];
			$value = $this->data['Member']['value'];
		}
		
		$this->set('field',$field);
		$this->set('value',$value);
	}
 
	function emails($authType = AUTH_MEM) {
		$this->adminOnly();
		
		$this->set("data", $this->Member->findAll("auth_type = '" . $authType . "'",array("first_name","last_name","email_address"),"last_name, first_name ASC"));
		$this->render();
	}
	
	function signup() {
		if ($this->Session->check('invited_by')) {
			$this->set('invited_by', $this->Session->read('invited_by'));
		}
		if (!empty($this->params['named'])) {
			$this->set('invited_by', $this->params['named']['invited_by']);
			$this->Session->write('invited_by', $this->params['named']['invited_by']);
		}
		$this->render();
	}
	
	function delete($id = null) {
		// make sure this is an administrator
		$this->adminOnly();
		
		if (!empty($this->data)) {
			//check the "are you sure"
			$this->Session->setFlash('The user was not deleted.');
			if ($this->data['Member']['delete_ok']) {
				//delete
				$this->Member->del($this->data['Member']['member_id']);
				$this->Session->setFlash('The member was removed.');
			}
			//redirect
			$this->redirect('/members/menu');
		}
		//no data, ask the user "are you sure"
		$this->set('member', $this->Member->find("Member.member_id = '" . $id . "'"));
		$this->render();
	}

	function labels($authType = 'member') {
		$q = ($authType === 'voting') ? 'votes = "1"' : "auth_type = '" . $authType . "'";
		$data = $this->Member->findAll($q,array("first_name","last_name","first_name_2","last_name_2","address_line1","address_line2","city","state","zip"),"last_name, first_name ASC");
		$labels = array();
		foreach($data as $member) {
			$label = array();
			$label['line1'] = $member['Member']['first_name'] . ' ' . $member['Member']['last_name'];
			if ($member['Member']['first_name_2'] != "" ) {
				if ($member['Member']['last_name_2'] == $member['Member']['last_name']) {
					$label['line1'] = $member['Member']['first_name'] . ' & ' . $member['Member']['first_name_2'] . ' ' . $member['Member']['last_name'];
				} else {
					$label['line1'] = $member['Member']['first_name'] . ' ' . $member['Member']['last_name'] . ' & ' . $member['Member']['first_name_2'] . ' ' . $member['Member']['last_name_2'];
				}
			}
			$label['line2'] = $member['Member']['address_line1'];
			if ($member['Member']['address_line2'] != "") {
				$label['line3'] = $member['Member']['address_line2'];
			}
			$label['line4'] = $member['Member']['city'] . ", " . $member['Member']['state'] . ' ' . $member['Member']['zip'];
			
			$labels[] = $label;
		}
		
		//print_pre($labels);
		
		include_once('libraries/class.label.php');
		$label = new Clabel();
		$label->makeLabel($labels,'pdf/out.pdf',false,false);
	}
	
	function login() {
		//Don't show the error message if no data has been submitted.
		$this->set('error', false);

		if ($this->Session->check("current_user")) {
			$this->Session->del("current_user");
		}
		
		// If a user has submitted form data:
		if (!empty($this->data)){
			// First, let's see if there are any users in the database
			// with the username supplied by the user using the form:
			$sql = 'SELECT member_id,username,auth_type,votes,volunteer,board_mem,banned,ban_reason,agree_del_id FROM members WHERE password=PASSWORD("'.$this->data['Member']['password'].'")';
			$someone = $this->Member->query($sql);
			// At this point, $someone is full of user data, or its empty.
			// Let's compare the form-submitted password with the one in
			// the database.
			foreach($someone as $member) {
				if(!empty($member['members']['username']) && $member['members']['username'] == $this->data['Member']['username']){
				// Note: hopefully your password in the DB is hashed,
				// so your comparison might look more like:
				// md5($this->data['User']['password']) == ...

				// This means they were the same. We can now build some basic
				// session information to remember this user as 'logged-in'.
				//$this->Session->delete('current_user');
					if ($member['members']['auth_type'] == AUTH_PROD) {
						$p = $this->Member->Producer->find("Producer.member_id = " . $member['members']['member_id']);
						$member['members']['producer_id'] = $p['Producer']['producer_id'];
					} else {
						if ($member['members']['banned']) {
							$this->Session->setFlash('<h3>You have been banned:</h3><p>' . $member['members']['ban_reason'] . '</p>');
							$this->redirect('/members/login');
							exit;
						}
					}
						//echo 'hi' + $this->Member->isPaid($member['members']['member_id']);
					$this->Session->write('current_user', $member['members']);
					$this->Session->write('current_delivery', Configure::read('Delivery.delivery_id'));
					$this->Session->write('delivery_open', Configure::read('Delivery.is_open'));
				// Now that we have them stored in a session, forward them on
				// to a landing page for the application.
					if ($this->deliveryId != $member['members']['agree_del_id']) {
						$this->redirect('/members/terms');
						exit();
					}
					if ($this->Session->check('goto')) {
						$g = $this->Session->read('goto');
						$this->Session->del('goto');
						$this->redirect($g);
						exit;
					} else {
						$this->redirect('/members/menu');
						exit();
					}
				}//else not found, keep looking
			}
			// Remember the $error var in the view? Let's set that to true:
			$this->set('error', true);
		}
	}

	function logout() {
		// Redirect users to this action if they click on a Logout button.
		// All we need to do here is trash the session information:

		$this->Session->delete('current_user');
		$this->Session->delete('current_basket');

		// And we should probably forward them somewhere, too...
		 
		$this->redirect('/');
		exit();
	}
	
	function terms() {
		if (!empty($this->data)) {
			$m = $this->Session->read('current_user');
			$this->Member->id = $m['member_id'];
			if ($this->data['Member']['agree_del_id'] == $this->deliveryId) {
				$this->Member->saveField('agree_del_id', $this->deliveryId);
				if ($this->Session->check('goto')) {
					$g = $this->Session->read('goto');
					$this->Session->del('goto');
					$this->redirect($g);
					exit;
				} else {
					$this->redirect('/members/menu');
					exit();
				}
			} else {
				$this->redirect('/members/logout');
				exit();
			}
		}
	}
	
	function menu() {
			//just a place holder to get us to the view.
			//$this->set('userInfo',$this->userInfo);
		$this->Session->write('go_back','');
		$this->Session->del('go_back');
				
	}
	
	function edit($id = null) {
		if (!$this->checkSession()) {
			$this->forceLogin();
		}
		$me = array();
		if ($id == null) {
			$me = $this->Member->findByUsername($this->userInfo['username']);
		} else {
			$member = $this->Member->find('Member.member_id = ' . $id);
			if($this->checkLevel(AUTH_ADMIN) or $this->isMe($member['Member']['username'])) {
				$me = $member;
				unset($member);
			} else {
				$this->notAuth();
			}
		}
		//at this point, we know we're logged in and set to either save data,
		//or display the 'update' form.
		if (!empty($this->data)) {
			if($this->data['Member']['member_id'] == $me['Member']['member_id'] or $this->checkLevel(AUTH_ADMIN)){ //check permissions one last time
				if($this->Member->save($this->data)) {
					$this->Session->setFlash('Member Information updated!','message_ok');
					$this->redirect('/members/menu');
				}
			}
		}
		$this->data = $me;
	}
	
	function editProducer($id = null) {
		if (!$this->checkSession()) {
			$this->forceLogin();
		}
		$me = array();
		if ($id == null) {
			$me = $this->Member->findByUsername($this->userInfo['username']);
		} else {
			$member = $this->Member->find('Member.member_id = ' . $id);
			if($this->checkLevel(AUTH_ADMIN) or $this->isMe($member['Member']['username'])) {
				$me = $member;
				unset($member);
			} else {
				$this->notAuth();
			}
		}
		$me['Producer']['list_producer'] = ($me['Producer']['donotlist_producer']) ? false : true;
		//at this point, we know we're logged in and set to either save data,
		//or display the 'update' form.
		if (!empty($this->data)) {
			if($this->data['Member']['member_id'] == $me['Member']['member_id'] or $this->checkLevel(AUTH_ADMIN)){ //check permissions one last time
			$d = $this->data;
			$d['Producer']['donotlist_producer'] = ($d['Producer']['list_producer']) ? false : true;
				if($this->Member->save($d)) {
		$this->Member->Producer->save($d);
					$this->Session->setFlash('Member Information updated!','message_ok');
					$this->redirect('/members/menu');
				}
			}
		}
		$this->data = $me;
	}
	
	function changePassword($id = null) {
		if (!$this->checkSession()) {
			$this->forceLogin();
		}
		$me = array();
		if ($id === null) {
			$me = $this->Member->findByUsername($this->userInfo['username']);
			if ($this->checkLevel(AUTH_ADMIN) && !empty($this->data)) {
				$me = $this->Member->find('Member.member_id = ' . $this->data['Member']['member_id']);
			}
		} else {
			$member = $this->Member->find('Member.member_id = ' . $id);
			if($this->checkLevel(AUTH_ADMIN) or $this->isMe($member['Member']['username'])) {
				$me = $member;
				unset($member);
			} else {
				$this->notAuth();
			}
		}
		//at this point, we know we're logged in and set to either save data,
		//or display the 'update' form.
		if (!empty($this->data)) {
			if($this->data['Member']['member_id'] == $me['Member']['member_id'] or $this->checkLevel(AUTH_ADMIN)){ //check permissions one last time
				$sql = 'SELECT member_id,username,auth_type FROM members WHERE password=PASSWORD("'.$this->data['Member']['old_password'].'")';
				$someone = $this->Member->query($sql);
				//print_r(array($someone,$me));
				if (!empty($someone)) {
					if ($someone[0]['members']['member_id'] != $me['Member']['member_id']) {
						$this->notAuth("The old password you entered was incorrect.	Password unchanged.");
					} else {
						if ($this->data['Member']['new_password'] != $this->data['Member']['passcheck']) {
							$this->notAuth("The new password and the check do not match.");
						} else {
							//we cleared the password check minefield!
							$sql = 'UPDATE members SET PASSWORD = PASSWORD( "' . $this->data['Member']['new_password'] . '" ) WHERE member_id =' . $me['Member']['member_id'];
							$this->Member->query($sql);
							$this->Session->setFlash('Password changed!','message_ok');
							$this->redirect('/members/menu');
						}
					}
				} else {
					$this->notAuth();
				}
			}
		}
		$this->data = $me;
	}
	
	function messenger($page = 1) {
		$this->adminOnly();
		
		$m = $page;
		$send = array(0=>'Everybody',AUTH_MEM=>'Users',AUTH_PROD=>'Producers',AUTH_ADMIN=>'Administrators');
		$this->set('send',$send);
		if (!empty($this->data)) { //we are either previewing, or ready to send.
			$body = $this->data['Message']['body'];
			$subject = $this->data['Message']['subject'];
			$this->set('message',array($subject,$body));
			$status = $this->data['submit'];
			if ($status == 'Send') { //send this baby!
					$auth_type = $this->data['Member']['auth_type'];
				//if ($search == 0) {
				//	$search = null;
				//}
				$order_open = null;
				$votes = null;
				$volunteer = null;
				$unpaid = null;
				if ((isset($this->data['Member']['hasBasket'])) and ($this->data['Member']['hasBasket'])) {
					$order_open = $this->Session->read('current_delivery');
				}
				if ((isset($this->data['Member']['votes'])) and ($this->data['Member']['votes'])) {
					$votes = true;
				}
				if ((isset($this->data['Member']['volunteer'])) and ($this->data['Member']['volunteer'])) {
					$volunteer = true;
				}
				if ((isset($this->data['Member']['unpaid'])) and ($this->data['Member']['unpaid'])) {
					$unpaid = true;
				}
				
				$find_options = compact('auth_type', 'order_open', 'votes', 'volunteer', 'unpaid');
				
				$s = $this->Member->getEmails($find_options,$page,&$m);
				
				$ret = $this->mailer('default', $subject, $body, $s, $this->data['Member']['testMode']);
				if ($this->data['Member']['testMode']) {
					print_r($find_options);
				}
				//echo($m);
				if ($ret[0] == 0) {
					$status = 'Sent!';
					$this->set('to',$ret[1]);
				} else {
					$status = "Error";
					$this->set('errors', $ret[1]);
				}
			}
			$this->set('status',$status);
		} else {//setup messaging form
			$this->data['Member']['auth_type'] = AUTH_MEM;
		}
		$this->set('data', $this->data);
		$this->set('more',$m);
		$this->render();
	}
	
	function mailer($view = null,$subject = SITE_NAME,$text = null,$to = array(), $debuging = false) {
		$ret = array();
		$view = (is_null($view)) ? 'default' : $view;
		if (!empty($to)) {
			
			extract(Configure::read('Email')); // gets out smtp_options, from, and replyTo
			
			$errors = array();
			foreach($to as $member) {
			  if (!preg_match('/^\s$/',$member['Member']['email_address']) && $member['Member']['email_address'] != null) {
			    $this->Email->to = $member['Member']['first_name'] . ' ' . $member['Member']['last_name'] . ' <' . $member['Member']['email_address'] . '>';
			    $ret[] = htmlentities($this->Email->to);
			  }
				$this->Email->smtpOptions = $smtp_options;
				$this->Email->delivery = 'smtp';
				$this->Email->from = $from;
				$this->Email->replyTo = $replyTo;
				$this->Email->subject = $subject;
				$this->Email->sendAs = 'text';
				$this->Email->template = $view;
				$this->set('text', $text);
				if (!$debuging) {
				 $this->Email->send();
				}
				if (!empty($this->Email->smtpError)) {
					$errors[] = array(htmlentities($this->Email->to), 'error' => $this->Email->smtpError);
					$this->Email->smtpError = null;
				}
				$this->Email->reset();
			}
			
			if (!empty($errors)) {
				return array(1, $errors);
			} else {
				return array(0,$ret);	
			}		
			
		} else { // if data is empty, then no addresses were passed in to email
			$this->Session->setFlash("No email addresses were passed to the mailer!");
			$this->redirect('/members/menu');
			//exit();
		}
	}
	
	function checkUsername() {
		$member = $this->Member->find('username = "' . $this->data['Member']['username'] . '"',array('username'));
		$this->set('un',$this->data['Member']['username']);
		$this->set("found", $member);
		$this->set('namelength',strlen($this->data['Member']['username']));
		$this->render('checkUsername','ajax');
	}
	
	function add($invite_id = null) {
		$member = $this->Member->find('username = "' . $this->data['Member']['username'] . '"',array('username'));
		$this->Member->set($this->data);
		if (!empty($member)) {
		    $this->Member->invalidate('username');
		}
		if ($this->data['Member']['password'] != $this->data['Member']['passcheck']) {
		    $this->Member->invalidate('password');
		}
		$this->data['Member']['auth_type'] = AUTH_MEM;
		$this->data['Member']['membership_date'] = date('Y-m-d');
		$this->data['Member']['paid_fee'] = date('Y-m-d', strtotime('-' . Configure::read('Membership.trial_period')));
		$this->data['Member']['member_id'] = null;
		$this->data['Member']['id'] = null;
		$this->Member->id = null;
		if (!$this->Member->save($this->data)) {
		    $this->set('errorMessage',"Something's not quite right there.");
		    $this->redirect('/members/signup');
		} else {
		    $sql = 'UPDATE members SET password=PASSWORD( "' . $this->data['Member']['password'] . '" ) WHERE username="' . $this->data['Member']['username'] . '"';
		    $this->Member->query($sql);
		    if (!$this->Session->check('current_user')){
		    	$this->Session->write("current_user",array('username'=>$this->data['Member']['username'],'auth_type'=>$this->data['Member']['auth_type'],'member_id'=>$this->Member->getLastInsertId()));
		    }
		    $this->Session->setFlash("Congrats - you've been added, and you are now logged on!");
		    //mail 'welcome' email
		    $this->mailer('welcome', 'Welcome to ' . Configure::read('site_name') . '!', null, array($this->data));
		    $this->redirect('/members/menu');
		    //echo 'member saved';
		}
	}
	
	function clearCurrentBasket() {
		$this->Session->delete('current_basket');
		$this->redirect('/members/menu');
	}
	
	function basket($member_id = null, $del_id = null) {
		$member = array();
		if (!$this->checkSession()) {
			$this->forceLogin();
		}
		if ($this->Session->check('current_basket') && is_null($member_id)) {
			$member_id = $this->Session->read('current_basket');
		}
		if ($this->checkLevel(AUTH_CASH) && ($member_id !== null)) {
		    $member = $this->Member->find('Member.member_id = ' . $member_id);
		    $this->Session->write('current_basket', $member_id);
		    $this->set('current_basket', $member_id);
		} else {
		    $member = $this->Member->find('username = "' . $this->userInfo['username'] . '"');
		    $member_id = $this->userInfo['member_id'];
		}
		$this->pageTitle = "My Basket";
		
		App::import('Model', 'Note');
		$note = new Note();
		if($this->checkLevel(AUTH_CASH)) {
			$p = new Producer();
			$this->set('producers',$p->findAll("Producer.donotlist_producer = '0'",null,"Member.business_name"));
		  $this->pageTitle = $member['Member']['first_name'] . ' ' . $member['Member']['last_name'] . "'s Basket";
			if(isset($this->data['Note'])) {
			// We're creating a note
				list($table_name, $table_id) = split('-', $this->data['Note']['table']);
				$this->data['Note']['table_id'] = $table_id;
				$this->data['Note']['table_name'] = $table_name;
				$note->save($this->data);
			}
			if(isset($this->data['BasketItem'])) {
			// We're modifying a BasketItem
				foreach($this->data['BasketItem'] as $key => $value) {
					list($field, $bId) = split('_',$key);
					$b = new BasketItem();
					$b->id = $bId;
					$b->saveField($field,$value);
					unset($b);
				}
				$b = new BasketItem();
				$b->breakOutDuplicates($member_id, 'member');
			}
		}
		
		$d = new Delivery();
		
		if (is_null($del_id)) {
			$del = $this->Session->read('current_delivery');
			$del = $d->findByDeliveryId($del);
		} else {
			$del = $d->findByDeliveryId($del_id);
		}
		
		$del_id = $del['Delivery']['delivery_id'];
		
		$neighbors = $d->find('neighbors', array("recursive" => -1, 'field'=>'Delivery.order_open', 'value' => $del['Delivery']['order_open']));
		
		$b = new BasketItem();
		$items = $b->c_find('member.member_id = ' . $member['Member']['member_id'], 'product', $del_id);
		unset($b);
		$notes = $note->getForMember($member_id);
		$sorting = array(array('producer','business_name'), array('product_list','product_name'));
		$this->set('sorting',$sorting);
		$this->set('notes', $notes);
		$this->set("member", $member);
		$this->set("items", $items);
		$this->set('neighbors', $neighbors);
		$this->set('del', $del);
		if ($this->params['url']['ext'] == 'pdf') {
			$this->set('lines', $items);
		}
	}
	
	function transfer($toId) {
		
		if (!$this->checkSession()) {
			$this->forceLogin();
		}
		if(!$this->checkLevel(AUTH_CASH)) {
			$this->Session->setFlash("You can't do that!");
			$this->redirect('/members/menu');
			exit();
		}
		if ($this->Session->check('current_basket')) {
			$member_id = $this->Session->read('current_basket');
		} else {
			$this->Session->write('current_basket', $toId);
			$this->redirect('/members/search');
			exit();
		}
		if (!empty($this->data)) {
			foreach($this->data['BasketItem'] as $bid => $swap) {
				if ($swap > 0) {
					$b = new BasketItem();
					$b->id = $bid;
					$b->saveField('member_id',$swap);
					unset($b);
				}
			}
		}
		    
		$members[] = $this->Member->find('Member.member_id = ' . $member_id);
		$members[] = $this->Member->find('Member.member_id = ' . $toId);
		
		$b = new BasketItem();
		$baskets[] = $b->c_find('member.member_id = ' . $member_id, 'product');
		$baskets[] = $b->c_find('member.member_id = ' . $toId, 'product');
		$this->set('baskets', $baskets);
		$this->set('members', $members);
	}
	
	function removeNote($note_id) {
		if (!$this->checkSession()) {
			$this->forceLogin();
		}
		if($this->checkLevel(AUTH_CASH)) {
			App::import('Model', 'Note');
			$note = new Note();
			$note->del($note_id);
		}
		$this->redirect('/members/basket');
	}
	
	function getLoggedInId() {
		if(!$this->checkSession()) {
			return false;
		} else {
			return $this->userInfo['member_id'];
		}
	}
	
	function forgotName() {
		if (!empty($this->data)) {
			$address = $this->data['Member']['email_address'];
			$member = $this->Member->find("email_address = '" . $address . "'");
			if (empty($member)) {
				$this->Session->setFlash("That email address does not belong to any member in our database.	Please re-check your address and try again.");
			} else {
				$username = $member['Member']['username'];
				
				extract(Configure::read('Email'));
				
				//email member
				if (!preg_match('/^\s$/',$member['Member']['email_address']) && $member['Member']['email_address'] != null) {
				  $this->Email->to = $member['Member']['first_name'] . ' ' . $member['Member']['last_name'] . ' <' .$member['Member']['email_address'] . '>';
				  $ret[] = $this->Email->to;
				}
				$this->Email->from = $from;
				$this->Email->subject = Configure::read('abbreviated_site_name') . ": Forgotten Username";
				$this->Email->template = 'forgotname';
				$this->Email->sendAs = 'text';
				$this->set('username', $username);
				
				$this->Email->send();
				
				//redirect
				$this->Session->setFlash("Your username has been sent to the email address on file.  It may take up to 5 minutes to arrive in your inbox.",'message_ok');
				$this->redirect('/');
				//$this->set('m',$member);
			}
		}
		$this->render();
	}
	
	function forgotPassword($username = null) {
		if (!empty($this->data) || $username != null) {
			$u = ($username != null) ? $username : $this->data['Member']['username'];
			$member = $this->Member->find("username = '" . $u . "'");
			if (empty($member)) {
				$this->Session->setFlash("That username does not belong to any member in our database.	Please re-check the name and try again.");
			} else {
				$security['password_generator'] = array(
					"C" => array('characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'minimum' => 4, 'maximum' => 6),
					"N" => array('characters' => '1234567890', 'minimum' => 2, 'maximum' => 2)
				);
				// Create the meta-password
				$sMetaPassword = "";
				$ahPasswordGenerator = $security['password_generator'];
				foreach ($ahPasswordGenerator as $cToken => $ahPasswordSeed)
				$sMetaPassword .= str_repeat($cToken, rand($ahPasswordSeed['minimum'], $ahPasswordSeed['maximum']));
		
				$sMetaPassword = str_shuffle($sMetaPassword);
	
				// Create the real password
				$arBuffer = array();
				for ($i = 0; $i < strlen($sMetaPassword); $i ++)
					$arBuffer[] = $ahPasswordGenerator[(string)$sMetaPassword[$i]]['characters'][rand(0, strlen($ahPasswordGenerator[$sMetaPassword[$i]]['characters']) - 1)];
				
				$newpass = implode("", $arBuffer);
				
				extract(Configure::read('Email'));
				
				//email member
				if (!preg_match('/^\s$/',$member['Member']['email_address']) && $member['Member']['email_address'] != null) {
				  $this->Email->to = $member['Member']['first_name'] . ' ' . $member['Member']['last_name'] . ' <' .$member['Member']['email_address'] . '>';
				  $ret[] = $this->Email->to;
				}
				$this->Email->from = $from;
				$this->Email->subject = Configure::read('abbreviated_site_name') . ": Forgotten Password";
				$this->Email->template = 'passreset';
				$this->Email->sendAs = 'text';
				$this->set('password', $newpass);
				
				$this->Email->send();
				
				$sql = 'UPDATE members SET PASSWORD = PASSWORD( "' . $newpass . '" ) WHERE member_id =' . $member['Member']['member_id'];
				$this->Member->query($sql);
							
				//redirect
				$this->Session->setFlash("Your new password has been sent to the email address on file.  It may take up to 5 minutes to arrive in your inbox.",'message_ok');
				$this->redirect('/');
				//$this->set('m',$member);
			}
		}
		$this->render();
	}
	
	function chartNumber() {
		$this->layout = 'ajax';
		$d = getdate();
		$y = $d['year'];
		$m = $d['mon'] - 6;
		if ($m < 1) {
			$m += 12;
			$y -= 1;
		}
		$months = array('');
		$members_added = array("Members Added");
		$members_paid = array("Members Paid");
		$members_total = array("Total Members");
				$q = "paid_fee > '" . date('Y-m-d', time() - 31536000) . "'";
		do {
			$m++;
			if ($m == 13) {
				$y++;
				$m = 1;
			}
			$start = mktime(0,0,0,$m,1,$y);
			$months[] = date("n/y",$start);
			$members_added[] = $this->Member->findCount('`auth_type` = "member" AND `membership_date`>=\'' . date('Y-m-d',$start) . '\' AND `membership_date`<=\'' . date('Y-m-t',$start) . '\' AND membership_discontinued = 0');
			$members_paid[] = $this->Member->findCount('`auth_type` = "member" AND `membership_date`<=\'' . date('Y-m-t',$start) . '\' AND `paid_fee` > \'' . date('Y-m-d', time() - 31536000) . '\' AND membership_discontinued = 0');
			$members_total[] = $this->Member->findCount('`auth_type` = "member" AND `membership_date`<=\'' . date('Y-m-t',$start) . '\' AND membership_discontinued = 0');
		} while ($y . '-' . $m != (date('Y-n')));
		$this->set('months',$months);
		$this->set('members_added',$members_added);
		$this->set('members_paid',$members_paid);
		$this->set('members_total',$members_total);
		$this->render();
	}
	
	function getMemberInfo($id) {
		return $this->Member->find('Member.member_id = ' . $id);
	}
	
	function paid($authType, $id = null) {
		
		if (!$this->checkSession()) {
			$this->forceLogin();
		}
		if(!$this->checkLevel(AUTH_CASH)) {
			$this->Session->setFlash("You can't do that!");
			$this->redirect('/members/menu');
			exit();
		}
		
		if (empty($id)) {
			$this->redirect('/members/menu');
			exit();
		}
		
		$m = $this->Member->find('Member.member_id = ' . $id);
		$last_paid = strtotime($m['Member']['paid_fee']);
		if ($last_paid + 31556926 < time()) {
			$paid_fee = date('Y-m-d',time());
		} else {
			$paid_fee = date('Y-m-d', $last_paid + 31556926);
		}
		$m['Member']['paid_fee'] = $paid_fee;
		$this->Member->save($m);
		$this->Session->setFlash(sprintf('%s %s  has been marked as paid, %s.', $m['Member']['first_name'], $m['Member']['last_name'], date('Y-m-d',time())),'message_ok');
		$redir = ($authType == 'search') ? '/members/menu' : '/members/show/' . $authType;
		$this->redirect($redir);
	}
	
	function checklist($page = 1) {
		
		if (!$this->checkSession()) {
			$this->forceLogin();
		}
		if(!$this->checkLevel(AUTH_CASH)) {
			$this->Session->setFlash("You can't do that!");
			$this->redirect('/members/menu');
			exit();
		}
		
		$this->pageTitle = 'Cashier Checklist ' . $page;
		
		$count = $this->Member->count_c_find(array('order_open' => $this->deliveryId));
		
		//NUM_CASHIERS is set in app_controller.php
		//$limit = ceil($count / NUM_CASHIERS);

		$members = $this->Member->c_find(array('order_open' => $this->deliveryId), null, 40, $page);
		$this->set('members', $members);
	}
	
	function tweets($page = 1) {
		$page_q = ($page != 1) ? '&page=' . $page : '';
		$search_results = file_get_contents('http://search.twitter.com/search.json?q=wmcoop' . $page_q);
		$results = json_decode($search_results, true);
		$this->set('page', $page);
		$this->set('results', $results);
	}
	
	function invite() {
		//must be logged in.
		if (!$this->checkSession()) {
			$this->forceLogin();
		}
		App::import('Sanitize');
		if (empty($this->data)) { //render the form
		
		} else { //send the email
			$addresses = explode(',', $this->data['Member']['emails']);
			extract(Configure::read('Email')); // gets out smtp_options, from, and replyTo
			$text = $this->data['Member']['text'];
		  $member = $this->Member->find('username = "' . $this->userInfo['username'] . '"');
			$this->set(compact('text','member'));
			foreach($addresses as $address) {
				$this->Email->to = trim($address);
				$this->Email->smtpOptions = $smtp_options;
				$this->Email->delivery = 'smtp';
				$this->Email->from = $from;
				$this->Email->replyTo = $replyTo;
				$this->Email->subject = Configure::read('site_name') . ' Invitation';
				$this->Email->sendAs = 'text';
				$this->Email->layout = 'invite';
				$this->Email->template = 'invite';
				//if (!$debuging) {
				$this->Email->send();
				//}
				if (!empty($this->Email->smtpError)) {
					$errors[] = array(htmlentities($this->Email->to), 'error' => $this->Email->smtpError);
					$this->Email->smtpError = null;
				}
				$this->Email->reset();
			}
			$this->Session->setFlash('Your invitation has been sent.  Thanks!', 'message_ok');
			$this->redirect('/members/menu');
		}
	}
	
}

?>